package com.tbit.uqbike.client.handler.borrowbikehandler;

import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigLogDao;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.UserBlackList;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfigLog;
import com.tbit.uqbike.client.service.UserBlackListService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lh2
 * @ClassName: BlackListCheckHandler
 * @Description: 黑名单校验处理器
 * @date 2023-07-26 05:41:54
 */
@Slf4j
@Component
public class BlackListCheckHandler extends AbstractCheckHandler {
    @Autowired
    private UserBlackListService userBlackListService;
    @Autowired
    private BorrowCheckConfigLogDao borrowCheckConfigLogMapper;

    @Override
    public ResultMsg handle(BorrowBikeVO vo, String serialNO) {
        log.info("【黑名单校验处理器】校验开始...");
        // 降级：如果配置了降级，则跳过此处理器，执行下一个处理器
        if (super.getConfig().getDown() == 1) {
            log.info("【黑名单校验处理器】被降级，已自动跳过！");
            return super.next(vo, serialNO);
        }

        User user = vo.getUser();
        /** 判断是否在黑名单 */
        UserBlackList userBlackList = userBlackListService.getByUserId(user.getUserId());
        if (userBlackList != null
                && DateTimeUtil.getTimeDF(DateTimeUtil.getNowTime(), userBlackList.getExpireTime() + " 00:00:00") > 0) {
            return ResultMsg.fail(-3036, "被加入黑名单，功能被限制", TraceUtil.getTraceIdByLocal());
        }
        List<UserBlackList> userBlackLists = userBlackListService.getByIdNO(user.getIdNO());
        if (userBlackLists.size() > 0) {
            for (UserBlackList userBlackListDB : userBlackLists) {
                if (userBlackListDB != null && DateTimeUtil.getTimeDF(DateTimeUtil.getNowTime(),
                        userBlackListDB.getExpireTime() + " 00:00:00") > 0) {
                    return ResultMsg.fail(-3036, "被加入黑名单，功能被限制",TraceUtil.getTraceIdByLocal());
                }
            }
        }
        log.info("【黑名单校验处理器】校验通过！");
        BorrowCheckConfigLog bccLog = borrowCheckConfigLogMapper.findByNameAndSerialNO(
                this.getConfig().getHandlerName(), serialNO);
        if (bccLog != null) {
            bccLog.setExecuteResult(1);
            borrowCheckConfigLogMapper.updateByPrimaryKeySelective(bccLog);
        }
        // 执行下一个处理器
        return super.next(vo, serialNO);
    }
}
